package com.zhen.servlet;

import com.zhen.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class UpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String id = req.getParameter("id");

        String username = req.getParameter("username");
        String oldusername = req.getParameter("oldusername");

        String name = req.getParameter("name");
        String oldname = req.getParameter("oldname");

        String password = req.getParameter("password");

        System.out.println("----UpdateServlet----");
        System.out.println("id="+id);
        System.out.println("username="+username);
        System.out.println("name="+name);
        System.out.println("password="+password);


        HttpSession session = req.getSession();
        if(!oldusername.equals(username)){
            System.out.println("账号修改为："+username);
            String sql="UPDATE `user` SET `username` = ? WHERE `id` = ?";
            System.out.println("成功");
            JdbcUtils.modify(sql,username,id);

        }

        if(!oldname.equals(name)){
            System.out.println("名称修改为："+name);
            String sql="UPDATE `user` SET `name` = ? WHERE `id` =?";
            JdbcUtils.modify(sql,name,id);
            session.setAttribute("UNAME",name);
        }

        if(!password.equals("")){
            System.out.println("密码修改为："+password);
            String sql="UPDATE `user` SET `password` = md5(?) WHERE `id` = ?;";
            JdbcUtils.modify(sql,password,id);
        }
        resp.sendRedirect("/zhen/index.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
